package la.bbs558.strategy.send;

import cn.hutool.core.util.RandomUtil;
import la.bbs558.entity.enums.ServerTypeEnum;
import la.bbs558.strategy.base.AbstractStrategy;
import la.bbs558.util.Objs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: Shanks
 * @date: 2024/1/25 14:40
 * @desc:
 */
@Slf4j
public abstract class AbstractSendStrategy extends AbstractStrategy<SendContext> {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    final public void handle(SendContext context) {
        init(context);
        doHandle(context);
        doAfter(context);
    }


    private void init(SendContext context) {
        String contextTo = context.getTo();
        ServerTypeEnum serverTypeEnum = context.getServerTypeEnum();
        long time = context.getTime();
        TimeUnit timeUnit = context.getTimeUnit();
        if(Objs.isAnyInvalid(contextTo,serverTypeEnum, time, timeUnit)){
            throw new IllegalArgumentException("发送验证码参数不合法");
        }
        generateCaptcha(context);
    }

    // 生成验证码
    protected void generateCaptcha(SendContext context){
        if(context.getCode() == null){
            String code = RandomUtil.randomNumbers(6);
            context.setCode(code);
        }
    }

    protected String getCodeKey(SendContext context){
        return context.getServerTypeEnum().getVerifyType().spaceName(context.getTo());
    }
    protected abstract void doHandle(SendContext context);
    protected void doAfter(SendContext context){
        long time = context.getTime();
        String code = context.getCode();
        TimeUnit timeUnit = context.getTimeUnit();
        String codeKey = getCodeKey(context);
        log.info("key={}|{}|验证码={}", codeKey,context.getServerTypeEnum().getDesc(), code);
        redisTemplate.opsForValue().set(codeKey, code, time, timeUnit);
    }



}
